import { tt } from "../../ttapi_interface/ttapi.js";
import * as tt2 from "../../ttapi_layer2/ttlayer2.js";
import { QUI_Container, QUI_IElement } from "../../ttapi_layer2/ttlayer2.js";
import * as EUI from "../eui/EUI.js";
import { Image_Editor } from "./image/creator.js";
import { Image_EditorUI } from "./image/editor.js";
import { Text_Editor } from "./text/creator.js";


//editor 不需要啥设计，因为每一个Editor 只有一个对应的Preview 会调用他，Editor 通常作为win的 PopModel来拉起就完了

//实现一个如下接口就得了

//重新规划一下
//FileEditor 负责编辑界面。
//编辑界面分和预览界面只是同一个界面的两种不同形态
//预览与编辑。
//因为某些情况下不能打开编辑界面，所以编辑界面的打开逻辑，由预览界面决定

export interface IFileEditor {
    getName(): string
    //关注哪些扩展名
    getCareExts(): string[];
    //初始化新的编辑器UI
    newEditorUI(): IEditorUI
    //在指定位置创建一个文件，可以弹UI
    newFileAsync(filename:string, win: EUI.EUI_Window):Promise<boolean>
    supportNewFile():boolean;
}
export interface EditorInfo {
    text: string;
    canopen: boolean;//是否能够进一步的Open
}
export interface IEditorUI {

    getFilename(): string;
    //step 1 init  此时处于预览状态
    OnInitAsync(filename: string, container: tt2.QUI_Container, win: EUI.EUI_Window): Promise<EditorInfo>;
    //step 2 open  此时处于打开状态
    Open(): Promise<boolean>;


    CanClose(): Promise<boolean>;
    Save(): Promise<boolean>;
    IsChange(): boolean;

    OnExitAsync(): Promise<void>;

    Reload(): Promise<void>;

}

export abstract class EditorBase implements IEditorUI {

    protected _filename: string;
    protected _container: tt2.QUI_Container
    protected _win: EUI.EUI_Window;
    getFilename(): string {
        return this._filename;
    }
    protected _inited: boolean;
    protected _tex: tt.ITexture;
    protected _change: boolean = false;
    async Reload() {

        await this.OnExitAsync();
        await this.OnInitAsync(this._filename, this._container, this._win);

    }

    async CanClose(): Promise<boolean> {
        return true;
    }

    async Save(): Promise<boolean> {
        return false;
    }
    async Open(): Promise<boolean> {
        return false;
    }
    IsChange(): boolean {
        return this._change;
    }


    abstract InitAsync(): Promise<{ ui: QUI_IElement, info: EditorInfo }>;
    abstract CleanAsync(): Promise<void>;

    async OnInitAsync(filename: string, container: tt2.QUI_Container, win: EUI.EUI_Window): Promise<EditorInfo> {
        this._filename = filename;
        this._container = container;
        this._win = win;

        try {
            let s = await this.InitAsync();
            this._container.addChild(s.ui);
            this._inited = true;
            return s.info;
        }
        catch (e) {
            console.log("遇到了错误:" + e);
            let label = EUI.EUI_Style.CreateBackWithText(JSON.stringify(e), new tt.Color(1, 0, 0, 1));
            this._container.addChild(label);
        }


    }



    async OnExitAsync(): Promise<void> {
        await this.CleanAsync();
    }



}